import socket
import re
from views import index
from http_class import HttpRequest, HttpResponse


class Router():

    def __init__(self, request):
        self.request = request

    def path(self, fix, view):
        """

        :param fix: 指定匹配路径
        :param view: 调用的视图
        :return:
        """
        if re.match(self.request.path, fix):
            # 匹配路径成功 ，调用指定的视图 view 等价于图方法
            return view(self.request)
        else:
            # 返回404的错误
            return HttpResponse('未匹配', 404)


class Ming(object):

    def __init__(self):
        self.socket_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.socket_client.bind(('192.168.130.32', 8000))
        self.socket_client.listen(128)
        self.request = HttpRequest()
        self.router = Router(self.request)

    def start(self):
        while True:
            print('运行的服务ip+port http://192.168.130.32:8000')
            conn, addr = self.socket_client.accept()
            data = conn.recv(1024).decode()
            # 请求解析
            self.request.pare(data)
            # 路由解析
            response = self.router.path('/', index)
            # 响应返回
            conn.send(response.response_data)
            conn.close()
            print('退出。。。。。')
